import cv2
import numpy as np
import os
import socket
import os
import shutil
import tkinter as tk
from tkinter import filedialog
import shutil
import time


FLAG = '$END$'
def sendFile_TCP(FILEPATH, ADDR, BUF=1024*64):
    sk = socket.socket()            # 初始化套接字
    sk.connect(ADDR)                # 尝试连接目标主机，如果失败会引发异常，这里为了简便没有进行异常处理
    sum = 0
    sp = '\\'
    if sp not in FILEPATH:
        sp = '/'
    filename = FILEPATH.split(sp)[-1]   # 分割路径字符串,获取文件名
    sk.send(filename.encode('utf-8'))
    with open(FILEPATH, 'rb') as f:
        while True:
            print('正在发送文件:{}  已发送 {} KB'.format(filename, int(sum/1024)))
            data = f.read(BUF)
            if not data:
                break
            sk.send(data)
            sum += len(data)
            time.sleep(0.1)
    sk.send(FLAG.encode())
    print('send_finished')
    os.system('title FileSender')
    sk.close()  # 关闭套接字


def main():
    addr = ('192.168.1.53', 20020)  # 目的地的IP和端口，端口不要动
    # 手动画框
    # 解析label_list，label_list要求按照画框的顺序写好
    root = r'predict_online'
    with open(os.path.join(root, "label_list.txt"), 'r') as file:
        label_list = file.readlines()
    label_list = [label.rstrip() for label in label_list]  # 去掉空字符
    label_list = [label for label in label_list if label != '']  # 去掉空行

    # 打开图像
    tk1 = tk.Tk()
    tk1.withdraw()
    img_path = filedialog.askopenfilename()
    src = img_path
    dst = os.path.join(root, 'origin_img.jpg')
    shutil.copy(src, dst)
    img_path_copy = dst
    img = cv2.imread(dst)
    # img = np.zeros((600, 800, 3), np.uint8)

    # 鼠标事件参数
    drawing = False
    x1, y1 = 0, 0
    mouse_param = {}
    mouse_param['ori_pos'] = None
    mouse_param['drawing'] = drawing
    mouse_param['x1'] = x1
    mouse_param['y1'] = y1
    mouse_param['img'] = img
    mouse_param['x2'] = 0
    mouse_param['y2'] = 0
    mouse_param['count'] = 0
    mouse_param['label_list'] = label_list

    # 鼠标画框
    cv2.namedWindow('img')
    cv2.setMouseCallback('img', on_mouse, mouse_param)
    while 1:
        cv2.imshow('img', img)
        k = cv2.waitKey(1) & 0xFF
        if k == 27:  # 按esc退出
            break
    cv2.destroyAllWindows()
    # 将画好的图片保存
    cv2.imwrite(os.path.join('predict_online', 'result.png'), mouse_param['img'], [int(cv2.IMWRITE_PNG_COMPRESSION), 0])

    # TCP发送文件
    result_file_path = os.path.join(root, 'result.png')
    print(result_file_path)
    sendFile_TCP(result_file_path, addr)
    # while True:
    #     print('【拖拽文件到此处】')
    #     path = input()
    #     sendFile_TCP(path, addr)


def on_mouse(event, x, y, flags, param):
    img = param['img']
    x1 = param['x1']
    y1 = param['y1']
    if event == cv2.EVENT_LBUTTONDOWN:  # 鼠标左键被按下
        param['drawing'] = True
        param['x1'], param['y1'] = x, y
        print('down')
    elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:  # 按住鼠标左键拖动
        if param['drawing'] is True:
            pass
            # cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 1)
        # print('move')
    elif event == cv2.EVENT_LBUTTONUP:
        param['drawing'] = False
        param['x2'] = x
        param['y2'] = y
        if param['count'] in range(len(param['label_list'])):
            cv2.rectangle(img, (x1, y1), (x, y), (255, 0, 0), 1)
            cv2.putText(img, param['label_list'][param['count']], (x1, y1), color=(0, 255, 0), fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=0.5)
        # 画框计数
        param['count'] += 1
        print('up')


if __name__ == '__main__':
    main()



